package com.whfc.ms.api.sys.service.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.face.uniview.UniviewFaceRecognitionService;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dto.AppEmpDTO;
import com.whfc.emp.entity.AppWorkPlan;
import com.whfc.emp.entity.ClassMeeting;
import com.whfc.emp.entity.ClassMeetingSign;
import com.whfc.emp.service.AppEmpService;
import com.whfc.emp.service.AppWorkPlanService;
import com.whfc.emp.service.ClassMeetingService;
import com.whfc.emp.service.ClassMeetingSignService;
import com.whfc.entity.dto.Apply.rep.ClassMeetingInfoRep;
import com.whfc.entity.dto.Apply.rep.QueryEmpSysIdDto;
import com.whfc.entity.dto.Apply.rep.StaffInfoRep;
import com.whfc.entity.dto.Apply.req.AppEntryApplicationReq;
import com.whfc.entity.dto.Apply.req.ClassMeetingCreateReq;
import com.whfc.entity.dto.Apply.req.MeetingDto;
import com.whfc.entity.dto.Apply.req.QuerycheckInListReq;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.service.SysUserService;
import com.whfc.ms.api.sys.dto.FaceCheckInReq;
import com.whfc.ms.api.sys.service.SysClassMeetingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.whfc.emp.dto.FaceCheckInResultDTO;
import com.whfc.emp.param.FaceCheckInParam;
import com.whfc.emp.service.FaceRecognitionCheckInService;

@Slf4j
@Service
public class SysClassMeetingServiceImpl implements SysClassMeetingService {
    @DubboReference(interfaceClass = AppWorkPlanService.class, version = "1.0.0", timeout = 30000)
    private AppWorkPlanService appWorkPlanService;

    @DubboReference(interfaceClass = ClassMeetingService.class, version = "1.0.0", timeout = 30000)
    private ClassMeetingService classMeetingService;

    @DubboReference(interfaceClass = ClassMeetingSignService.class, version = "1.0.0", timeout = 30000)
    private ClassMeetingSignService classMeetingSignService;

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0", timeout = 30000)
    private SysUserService sysUserService;

    @DubboReference(interfaceClass = AppEmpService.class, version = "1.0.0", timeout = 30000)
    private AppEmpService appEmpService;

    /**
     * 人脸识别签到
     */
    @DubboReference(interfaceClass = FaceRecognitionCheckInService.class, version = "1.0.0", timeout = 30000)
    private FaceRecognitionCheckInService faceRecognitionCheckInService;

    @Autowired
    private UniviewFaceRecognitionService univiewFaceRecognitionService;

    @Override
    public List<AppWorkPlan> selectAppWorkPlanList(SysUser user, Integer id) {
        return appWorkPlanService.selectAppWorkPlanList(1, user.getId(), id);
    }
    @Override
    public String saveClassMeeting(SysUser user, ClassMeetingCreateReq req) {
        ClassMeeting record = new  ClassMeeting();
        record.setMeetingName(req.getMeetingName()); //班会名称
        record.setPlanId(req.getPlanId());// 计划id
        record.setMeetingType(req.getMeetingType());// 班会类型
        record.setCreateUser(user.getId());
        // 存储班会信息
        int id = classMeetingService.insertSelective(record);
        if(id == 0){
            return "创建班会失败";
        }

        for (Integer participantId : req.getParticipantIds()) {
            ClassMeetingSign msRecord = new ClassMeetingSign();
            msRecord.setMeetingId(id);// 班会Id
            msRecord.setUserId(participantId);// 参会人员Id
            msRecord.setCreatorId(user.getId());
            classMeetingSignService.insertSelective(msRecord);
        }
        return "创建班会成功";
    }

    @Override
    public List<ClassMeetingInfoRep> queryClassMeeting(SysUser user, String startTimeBegin,String startTimeEnd) {
        //查看当前登录人是否 是普通员工
        SysUser sysUser = sysUserService.selectByPrimaryKey(user.getId());
        List<ClassMeetingInfoRep> classMeetingInfoReps = null;
        if(Objects.equals(sysUser.getUserType(),"4")){
            classMeetingInfoReps = classMeetingService.selectByMeetingDateEndUserId(startTimeBegin, startTimeEnd, user.getId());
        }else {
            classMeetingInfoReps = classMeetingService.selectByMeetingDateEndCreateUser(startTimeBegin,startTimeEnd,user.getId());
        }
        if(CollectionUtils.isEmpty(classMeetingInfoReps)) {
            return null;
        }

        for (ClassMeetingInfoRep classMeetingInfoRep : classMeetingInfoReps) {
            classMeetingInfoRep.setPlanName(appWorkPlanService.selectById(classMeetingInfoRep.getPlanId()).getPlanName());
            classMeetingInfoRep.setAttendeeList(sysUserService.selectNamePrimaryKey(Arrays.asList(classMeetingInfoRep.getAttendees())));
            classMeetingInfoRep.setCreator(sysUserService.getUserById(Integer.valueOf(classMeetingInfoRep.getCreator())).getUsername());
        }
        return classMeetingInfoReps;
    }

    @Override
    public String checkIn(SysUser user,Integer id) {
        ClassMeetingSign classMeetingSign = classMeetingSignService.selectByPrimaryIdAndUserId(id, user.getId());
        classMeetingSign.setSignStatus(1);
        classMeetingSignService.updateByPrimaryKey(classMeetingSign);
        return "签到成功";
    }

    @Override
    public FaceCheckInResultDTO faceCheckIn(SysUser user, FaceCheckInReq req) {
        // 构建人脸识别签到参数
        FaceCheckInParam param = new FaceCheckInParam();
        param.setMeetingId(req.getId());
        param.setEmpId(user.getId());
        param.setUserName(user.getUsername());
        param.setFaceImage(req.getFaceImage());
        param.setCreatorId(user.getId());

        // 调用dubbo服务进行人脸识别签到
        return faceRecognitionCheckInService.faceCheckIn(param);
    }

    @Override
    public ClassMeetingInfoRep queryMeeting(Integer id) {
        ClassMeetingInfoRep classMeetingInfoRep = classMeetingService.selectByMeetingDateEndId(id);
        classMeetingInfoRep.setPlanName(appWorkPlanService.selectById(classMeetingInfoRep.getPlanId()).getPlanName());
        classMeetingInfoRep.setAttendeeList(sysUserService.selectNamePrimaryKey(Arrays.asList(classMeetingInfoRep.getAttendees())));
        classMeetingInfoRep.setCreator(sysUserService.getUserById(Integer.valueOf(classMeetingInfoRep.getCreator())).getUsername());
        return classMeetingInfoRep;
    }

    @Override
    public String addFilePath(Integer id, String filePath) {
        ClassMeeting classMeeting = classMeetingService.selectByPrimaryKey(id);
        classMeeting.setFilePath(filePath);
        classMeetingService.updateByPrimaryKey(classMeeting);
        return "1";
    }

    @Override
    public List<StaffInfoRep> querycheckInList(Integer id) {
        List<ClassMeetingSign> classMeetingSign = classMeetingSignService.selectSignByMeetingId(id);
        List<String> userIds = new ArrayList<>();
        List<StaffInfoRep> staffInfoReps = new ArrayList<>();

        for (ClassMeetingSign classMeetingSign1 : classMeetingSign) {
            userIds.add(String.valueOf(classMeetingSign1.getUserId()));
        }
        List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(userIds);
        for (QueryEmpSysIdDto queryEmpSysId : appEmpIds) {
            StaffInfoRep  staffInfoRep = new StaffInfoRep();
            AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysId.getAppEmpId());
            staffInfoRep.setEmpId(empInfo.getEmpId());
            staffInfoRep.setIdCardNo(empInfo.getIdCardNo());
            staffInfoRep.setGender(empInfo.getGender());
            staffInfoRep.setName(empInfo.getEmpName());
            staffInfoRep.setHardwareNumber(empInfo.getSn());
            staffInfoRep.setPosition(empInfo.getWorkTypeName());
            for (ClassMeetingSign classMeet : classMeetingSign) {
                if(Objects.equals(classMeet.getUserId(),queryEmpSysId.getSysUserId())){
                    staffInfoRep.setSignStatus(classMeet.getSignStatus());
                }
            }
            staffInfoReps.add(staffInfoRep);
        }

        return staffInfoReps;
    }

    @Override
    public PageData<MeetingDto> list(AppEntryApplicationReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<MeetingDto> dtoList = classMeetingService.meetingList(req);
        if(CollectionUtils.isEmpty(dtoList)) {
            return null;
        }

        for (MeetingDto meetingDto : dtoList) {
            // 获取参会人员
            List<String> participantList = new  ArrayList<>();
            if(meetingDto.getParticipantIds().contains(",")){
                participantList = Arrays.asList(meetingDto.getParticipantIds().split(","));
            }else {
                participantList = Arrays.asList(meetingDto.getParticipantIds());
            }
            SysUser sysUser = sysUserService.selectByPrimaryKey(Integer.valueOf(meetingDto.getCreateUser()));
            meetingDto.setCreateUser(sysUser.getUsername());
            // 参会人员列表
            List<String> participants = new  ArrayList<>();
            List<QueryEmpSysIdDto> appEmpIds = sysUserService.getAppEmpEmpNamesIdList(participantList);
            for (QueryEmpSysIdDto queryEmpSysId : appEmpIds) {
                AppEmpDTO empInfo = appEmpService.getEmpInfo(queryEmpSysId.getAppEmpId());
                participants.add(empInfo.getEmpName());
            }
            meetingDto.setParticipants(participants);

            // 创建人(也就是班组长) || 联系方式手机号
            List<QueryEmpSysIdDto> createUsers = sysUserService.getAppEmpEmpNamesIdList(Arrays.asList(meetingDto.getCreateUser()));
            for (QueryEmpSysIdDto appEmpId : createUsers) {
                AppEmpDTO empInfo = appEmpService.getEmpInfo(appEmpId.getAppEmpId());
                meetingDto.setCreateUser(empInfo.getEmpName());
                meetingDto.setPhone(empInfo.getPhone());
            }
        }
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(dtoList));
    }
}